Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for encoding/decoding compressed EC keys #57

Open
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

huskcasaca
Copy link
Contributor

@huskcasaca huskcasaca commented Dec 13, 2024

This PR add support for Compressed and Uncompressed(default) format under RAW EC Public Key.

  • JDK(BC)
  • WebCrypto
  • Apple (Not Supported)
  • OpenSSL3

Comment on lines +211 to +243
internal fun ECParameterSpec.decodePoint(bytes: ByteArray): ECPoint {
val fieldSize = curveOrderSize()
return when (bytes[0].toInt()) {
0x02, // compressed evenY
0x03, // compressed oddY
-> {
check(bytes.size == fieldSize + 1) { "Wrong compressed key size ${bytes.size}" }
val p = (curve.field as ECFieldFp).p
val a = curve.a
val b = curve.b
val x = BigInteger(1, bytes.copyOfRange(1, bytes.size))
var y = x.multiply(x).add(a).multiply(x).add(b).mod(p).modSqrt(p)
if (y.testBit(0) != (bytes[0].toInt() == 0x03)) {
y = p.subtract(y)
}
ECPoint(x, y)
}
0x04, // uncompressed
-> {
check(bytes.size == fieldSize * 2 + 1) { "Wrong uncompressed key size ${bytes.size}" }
val x = bytes.copyOfRange(1, fieldSize + 1)
val y = bytes.copyOfRange(fieldSize + 1, fieldSize + 1 + fieldSize)
ECPoint(BigInteger(1, x), BigInteger(1, y))
}
else -> error("Unsupported key type ${bytes[0].toInt()}")
}
}

internal fun BigInteger.modSqrt(p: BigInteger): BigInteger {
check(p.testBit(0) && p.testBit(1)) { "Unsupported curve modulus" } // p ≡ 3 (mod 4)
return modPow(p.add(BigInteger.ONE).shiftRight(2), p) // Tonelli-Shanks
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BC is added as a provider without some API access so it requires manually calculating y.

@huskcasaca huskcasaca marked this pull request as ready for review December 18, 2024 03:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant